﻿using CSRedis;
using Newtonsoft.Json;

namespace MES.Process.API
{
    /// <summary>
    /// Redis工具类
    /// </summary>
    public static class RedisUtil
    {
        private static CSRedisClient _client;
        /// <summary>
        /// 静态构造函数，只有第一次访问此类的时候才会被执行，而且只会执行一次
        /// </summary>
        static RedisUtil()
        {
            var builder = new ConfigurationBuilder()
    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) // Set the base path to the directory where the app is running
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); // Load appsettings.json

            var configuration = builder.Build();
            _client = new CSRedisClient(configuration["RedisConnection"]);
        }
        /// <summary>
        /// 写入Redis
        /// </summary>
        /// <typeparam name="T">s数据类型</typeparam>
        /// <param name="key">缓存的键</param>
        /// <param name="data">需要缓存的数据</param>
        /// <param name="expireTime">过期时间</param>
        public static bool Set<T>(string key, T data, TimeSpan? expireTime = null)
        {
            if (data == null) return false;
            var json = JsonConvert.SerializeObject(data);
            return expireTime == null ? _client.Set(key, json)
               : _client.Set(key, json, expireTime.Value);

        }

        /// <summary>
        /// 读取缓存数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">缓存的键</param>
        /// <returns></returns>
        public static T? Get<T>(string key)
        {
            var json = _client.Get(key);
            if (json == null)
            {
                return default;
            }
            return JsonConvert.DeserializeObject<T>(json)!;
        }
        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key"></param>
        public static void Del(string key)
        {
            _client.Del(key);
        }

    }
}
